/// 聊天详情页面
/// 显示与特定用户的对话消息及消息输入框
library;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:chat_project/config/theme_config.dart';
import 'package:chat_project/providers/auth_provider.dart';
import 'package:chat_project/providers/chat_provider.dart';
import 'package:chat_project/models/conversation_model.dart';
import 'package:chat_project/widgets/message_input.dart';
import 'package:chat_project/widgets/message_bubble.dart';
import 'dart:async';

class ChatScreen extends StatefulWidget {
  final String conversationId;
  final String userId;
  
  const ChatScreen({
    super.key,
    required this.conversationId,
    required this.userId,
  });
  
  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> with WidgetsBindingObserver, AutomaticKeepAliveClientMixin {
  final ScrollController _scrollController = ScrollController();
  bool _isFirstLoad = true;
  Timer? _messageCheckTimer;
  
  @override
  bool get wantKeepAlive => true; // 保持页面状态
  
  @override
  void initState() {
    super.initState();
    // 注册生命周期观察者
    WidgetsBinding.instance.addObserver(this);
    
    // 在initState中选择当前对话
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final chatProvider = Provider.of<ChatProvider>(context, listen: false);
      
      // 打印用户ID和会话ID
      print('ChatScreen初始化: conversationId=${widget.conversationId}, userId=${widget.userId}');
      
      // 选择对话
      chatProvider.selectConversation(widget.conversationId, widget.userId);
      
      // 确保Socket连接
      chatProvider.reconnectSocket();
      
      // 启动定期检查消息
      _startMessageCheck();
    });
  }
  
  // 定期检查新消息
  void _startMessageCheck() {
    _stopMessageCheck();
    
    // 每5秒检查一次新消息
    _messageCheckTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
      if (mounted) {
        final chatProvider = Provider.of<ChatProvider>(context, listen: false);
        
        // 确保socket连接
        if (!chatProvider.socketConnected) {
          chatProvider.reconnectSocket();
        }
        
        // 刷新消息
        chatProvider.loadMessages(widget.userId);
      }
    });
  }
  
  // 停止定期检查
  void _stopMessageCheck() {
    _messageCheckTimer?.cancel();
    _messageCheckTimer = null;
  }
  
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    
    // 获取消息后滚动到底部
    if (_isFirstLoad) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToBottom();
        _isFirstLoad = false;
      });
    }
  }
  
  @override
  void didUpdateWidget(ChatScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // 如果会话ID变化，重新加载消息
    if (oldWidget.conversationId != widget.conversationId || 
        oldWidget.userId != widget.userId) {
      _isFirstLoad = true;
      final chatProvider = Provider.of<ChatProvider>(context, listen: false);
      chatProvider.selectConversation(widget.conversationId, widget.userId);
      
      // 重新启动消息检查
      _startMessageCheck();
    }
  }
  
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    
    final chatProvider = Provider.of<ChatProvider>(context, listen: false);
    
    // 应用回到前台时重新连接Socket
    if (state == AppLifecycleState.resumed) {
      chatProvider.reconnectSocket();
      
      // 重新加载消息
      chatProvider.loadMessages(widget.userId);
      
      // 重启消息检查
      _startMessageCheck();
    } else if (state == AppLifecycleState.paused) {
      // 应用进入后台时暂停消息检查
      _stopMessageCheck();
    }
  }
  
  @override
  void dispose() {
    // 停止消息检查
    _stopMessageCheck();
    
    // 移除生命周期观察者
    WidgetsBinding.instance.removeObserver(this);
    _scrollController.dispose();
    super.dispose();
  }
  
  // 当收到新消息时，滚动到底部
  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }
  
  @override
  Widget build(BuildContext context) {
    super.build(context); // AutomaticKeepAliveClientMixin要求
    
    final chatProvider = Provider.of<ChatProvider>(context, listen: true); // 确保监听变化
    final authProvider = Provider.of<AuthProvider>(context);
    final currentUser = authProvider.user;
    
    // 获取当前对话
    final conversation = chatProvider.conversations.firstWhere(
      (conv) => conv.id == widget.conversationId,
      orElse: () => Conversation(
        id: widget.conversationId,
        contact: authProvider.user!,
      ),
    );
    
    // 获取消息列表
    final messages = chatProvider.getMessages(widget.userId);
    
    // 对方是否正在输入
    final isTyping = chatProvider.isUserTyping(widget.userId);
    
    // 当消息列表更新时，滚动到底部
    if (messages.isNotEmpty) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToBottom();
      });
    }
    
    return Scaffold(
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              conversation.contact.username,
              style: const TextStyle(
                fontSize: ThemeConfig.fontSizeMedium,
                fontWeight: FontWeight.bold,
              ),
            ),
            if (isTyping)
              const Text(
                '正在输入...',
                style: TextStyle(
                  fontSize: ThemeConfig.fontSizeSmall,
                  fontWeight: FontWeight.normal,
                ),
              )
            else
              Text(
                conversation.contact.isOnline ? '在线' : '离线',
                style: TextStyle(
                  fontSize: ThemeConfig.fontSizeSmall,
                  fontWeight: FontWeight.normal,
                  color: conversation.contact.isOnline
                      ? ThemeConfig.successColor
                      : ThemeConfig.textSecondaryColor,
                ),
              ),
          ],
        ),
        backgroundColor: ThemeConfig.primaryColor,
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            tooltip: '刷新消息',
            onPressed: () {
              // 手动刷新消息
              final chatProvider = Provider.of<ChatProvider>(context, listen: false);
              chatProvider.loadMessages(widget.userId);
              // 确保socket连接
              chatProvider.reconnectSocket();
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('正在刷新消息...')),
              );
            },
          ),
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: () {
              // 显示用户资料
            },
          ),
          IconButton(
            icon: const Icon(Icons.more_vert),
            onPressed: () {
              // 显示更多选项菜单
              _showOptionsMenu(context);
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 消息列表
          Expanded(
            child: NotificationListener<ScrollNotification>(
              onNotification: (ScrollNotification scrollInfo) {
                // 当用户滚动到顶部时，加载更多历史消息（可能的扩展）
                if (scrollInfo.metrics.pixels == scrollInfo.metrics.minScrollExtent &&
                    !chatProvider.isLoading) {
                  // 这里可以添加加载更多历史消息的逻辑
                }
                return true;
              },
              child: RefreshIndicator(
                onRefresh: () async {
                  // 刷新时重新连接Socket并加载消息
                  final chatProvider = Provider.of<ChatProvider>(context, listen: false);
                  chatProvider.reconnectSocket();
                  await chatProvider.loadMessages(widget.userId);
                  return;
                },
                child: chatProvider.isLoading && messages.isEmpty
                    ? const Center(child: CircularProgressIndicator())
                    : messages.isEmpty
                        ? ListView(
                            physics: const AlwaysScrollableScrollPhysics(),
                            children: const [
                              SizedBox(height: 100),
                              Center(
                                child: Text('暂无消息，开始聊天吧！'),
                              ),
                            ],
                          )
                        : ListView.builder(
                            controller: _scrollController,
                            padding: const EdgeInsets.all(ThemeConfig.paddingRegular),
                            itemCount: messages.length,
                            itemBuilder: (context, index) {
                              final message = messages[index];
                              final isMe = message.sender.id == currentUser?.id;
                              
                              // 使用Key确保Flutter能识别消息的变化
                              return MessageBubble(
                                key: ValueKey(message.id),
                                message: message,
                                isMe: isMe,
                                showAvatar: true,
                              );
                            },
                          ),
              ),
            ),
          ),
          
          // 正在输入指示器
          if (isTyping)
            Container(
              padding: const EdgeInsets.symmetric(
                horizontal: ThemeConfig.paddingRegular,
                vertical: 4,
              ),
              alignment: Alignment.centerLeft,
              child: Text(
                '${conversation.contact.username} 正在输入...',
                style: const TextStyle(
                  fontSize: ThemeConfig.fontSizeSmall,
                  fontStyle: FontStyle.italic,
                  color: ThemeConfig.textSecondaryColor,
                ),
              ),
            ),
          
          // 消息输入框
          if (currentUser != null)
            MessageInput(
              onSend: (content, type) {
                chatProvider.sendMessage(content, currentUser, type: type);
                // 确保UI更新后滚动到底部
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  _scrollToBottom();
                });
              },
              onTypingChanged: (isTyping) {
                chatProvider.sendTypingStatus(isTyping);
              },
            ),
        ],
      ),
    );
  }
  
  // 显示更多选项菜单
  void _showOptionsMenu(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ListTile(
            leading: const Icon(Icons.search),
            title: const Text('搜索'),
            onTap: () {
              Navigator.pop(context);
              // 实现搜索功能
            },
          ),
          ListTile(
            leading: const Icon(Icons.delete_outline),
            title: const Text('清空聊天记录'),
            onTap: () {
              Navigator.pop(context);
              _showConfirmDialog(
                context,
                '确认清空',
                '是否要清空与该用户的所有聊天记录？',
                () {
                  // 实现清空聊天记录功能
                },
              );
            },
          ),
          ListTile(
            leading: const Icon(Icons.block),
            title: const Text('屏蔽该用户'),
            onTap: () {
              Navigator.pop(context);
              _showConfirmDialog(
                context,
                '确认屏蔽',
                '是否要屏蔽该用户？屏蔽后将不再收到该用户的消息。',
                () {
                  // 实现屏蔽用户功能
                },
              );
            },
          ),
          const SizedBox(height: 8),
        ],
      ),
    );
  }
  
  // 显示确认对话框
  void _showConfirmDialog(
    BuildContext context,
    String title,
    String content,
    VoidCallback onConfirm,
  ) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              onConfirm();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
} 